package com.thingsgrid.appmonitor.service.impl;

import com.thingsgrid.appmonitor.entity.DeviceInFo;
import com.thingsgrid.appmonitor.entity.DeviceMonitor;
import com.thingsgrid.appmonitor.mapper.DeviceMapper;
import com.thingsgrid.appmonitor.service.DeviceService;
import com.thingsgrid.device.entity.Device;
import lombok.AllArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 设备状态监控实现类
 */
@Service
@AllArgsConstructor
public class DeviceServiceImpl implements DeviceService {
	private DeviceMapper deviceMapper;
	private MongoTemplate mongoTemplate;

	/**
	 * 设备监控分页
	 *
	 * @param device
	 * @return
	 */
	@Override
	public DeviceInFo getDeviceInfoByDeviceId(Device device) {
		DeviceInFo deviceInFo = new DeviceInFo();//初始化实体类
		String device_id = device.getDeviceId();//从device中取出deviceID
		Query query = new Query();
		query.addCriteria(Criteria.where("deviceId").is(device_id));
		//把deviceid传入,MongoDB通过deviceId查询设备监控信息.
		List<DeviceMonitor> deviceMonitor = mongoTemplate.find(query, DeviceMonitor.class, "device_monitor");
		int applicationNum = deviceMapper.getApplicationNum(device_id);//计算APP数量
		deviceInFo.setApplicationNum(applicationNum);
		String deviceName = device.getDeviceName();
		deviceInFo.setDeviceId(device_id);
		deviceInFo.setDeviceName(deviceName);
		//对deviceMonitor集合进行升序排序
		Collections.sort(deviceMonitor, new Comparator<DeviceMonitor>() {
			@Override
			public int compare(DeviceMonitor o1, DeviceMonitor o2) {
				if (o1.getCreateTime() > o2.getCreateTime()) {
					return -1;
				}
				if (o1.getCreateTime() == o2.getCreateTime()) {
					return 0;
				}
				return 1;
			}
		});
		for (int i = 0; i < deviceMonitor.size(); i++) {
			//取排序的第一条数据
			String cpu = deviceMonitor.get(0).getDeviceCpu();//cpu使用率
			String memory = deviceMonitor.get(0).getDeviceMemory();//空间使用率
			String disk = deviceMonitor.get(0).getDeviceDisk();//内存使用率
			String flow = deviceMonitor.get(0).getDeviceFlow();//流量
			//把数据赋值给实体类属性
			deviceInFo.setDeviceCpu(cpu);//给所需参数赋值
			deviceInFo.setDeviceMemory(memory);
			deviceInFo.setDeviceDisk(disk);
			deviceInFo.setDeviceFlow(flow);

		}
		//返回实体类对象实例
		return deviceInFo;

	}

}
